<template>
	<view>
		<view class="countdown">
			<view class="zw">
			</view>
			<view class="countdown-box" :style="{'color':countColor}">
				<text>考试倒计时</text>
				<uni-countdown @timeup="timeUpChang" @changTime="changTime" :color="countColor" :font-size="15"
					:showDay="false" :minute="120" />
			</view>
		</view>
		<view class="list-box">
			<view class="list">
				<view :ref="'jump'+index" :class="'jump'+index" v-for="(item, index) in list">
					<uni-section :sectionHeade="'sectionHeade'"
						:title="index + 1 + (item.tqType == '1' ?'.[单选题]':  (item.tqType == '2' ? '.[多选题]':'.[判断题]')) +item.title" type="line">
						<view class="uni-px-5 uni-pb-5">
							<kevy-radio :modeType="modeType" :items="item" :idx="index" :fontSize="28"
								color="#272727" :iconSize="30" iconColor="#329cfe" @radioClick="myClick($event, index)"></kevy-radio>
						</view>
					</uni-section>
				</view>
			</view>
		</view>
		<view class="btm-btn">
			<button class="btn" @click="submitPaper">交卷</button>
			<button class="btn" @click="AnswersListShow">答题卡</button>
		</view>
		<!-- 答题卡 -->
		<uni-popup ref="AnswersListPopup" background-color="#fff" type="top" @change="AnswersListChange">
			<view @click="closeAnswersList" class="iconfont icon-cuowu closeIcon"></view>
			<view class="popup-content">
				<text class="text">答题卡</text>
				<template v-if="modeType === '0'">
					<view class="ListBtns">
						<button @click="clickItem(item, 0, index)" class="btnMin"
							:class="{'btnGreen':!!item.userAnswer && item.userAnswer,}" size="mini"
							v-for="(item, index) in list">{{index+1}} </button>
					</view>
				</template>
				<template v-else>
					<view class="ListBtns">
						<button @click="clickItem(item, 0, index)" class="btnMin"
							:class="{'btnGreen':!!item.userAnswer && item.userAnswer == item.bzAnswer, 'btnRad': !!item.userAnswer && item.userAnswer !== item.bzAnswer}"
							size="mini" v-for="(item, index) in list">{{index+1}} </button>
					</view>
				</template>
			</view>
		</uni-popup>
		<!-- 交卷====有未做题目 -->
		<uni-popup ref="paperPopup" type="center">
			<view class="paper-box">
				<view @click="closePaperClose" class="iconfont icon-cuowu closeIcon"></view>
				<view class="submitPopupTxt">
					<text class="popup-title" style="color: #f00;">交卷提示</text>
					<view class="popup-sub">你还有<text style="color: #f00;">{{unSelectedNum.length}}</text>道题没做，确定交卷吗？
					</view>
				</view>
				<view class="paper-list">
					<span class="" v-for="(item, index) in list">
						<button v-if="!item.userAnswer" @click="clickItem(item, 1, index)" class="btnMin"
							size="mini">{{index+1}} </button>
					</span>

				</view>
				<view class="submitPopupBtn">
					<button class="close-btn" @click="closePaperClose" type="default">取消</button>
					<button class="submit-btn" @click="confirmPaper" type="primary">确定交卷</button>
				</view>
			</view>
		</uni-popup>
		<!-- 考试成绩 :is-mask-click="false" -->
		<uni-popup ref="submitPopup" :is-mask-click="false" type="center">
			<view class="submit-popup-box">
				<view class="submitPopupTxt">
					<text class="popup-title">考试成绩</text>
					<view class="popup-sub">
						<text class="submit-name">{{ userInfo.username }}-{{ userInfo.IDcardNum }}</text>
						<text class="submit-type">{{ opcName }}</text>
					</view>
					<view class="fraction">
						<text :style="{'color': passNum>chooseCorrectly.length?'#f00':'#329cfe'}"
							class="fraction-num">{{ chooseCorrectly.length }}</text>分
					</view>
					<text class="timePaper">答题用时：{{ examinationTime }}</text>
					<view class="prompt-box">
						<view style="background: #f00;color: #fff;" class="prompt-box-txt">
							<text>答错</text>
							<text>{{ selectionError.length }}</text>
						</view>
						<view style="background: #329cfe;color: #fff;" class="prompt-box-txt">
							<text>答对</text>
							<text>{{ chooseCorrectly.length }}</text>
						</view>
						<view v-if="unSelectedNum.length > 0" style="background-color: #b1b1b1;color: #fff;"
							class="prompt-box-txt">
							<text>未答</text>
							<text>{{ unSelectedNum.length }}</text>
						</view>
					</view>
					<view class="submit-list">
						<button size="mini" @click="practiceError" class="list-btn" type="warn">错题练习</button>
						<button size="mini" @click="lockpaper" class="list-btn" type="primary">查看试卷</button>
						<button @click="closeBlack" size="mini" class="list-btn" type="default">关 闭</button>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	// import atob from 'atob'
	import mock from '@/static/mockTM.json'
	import {
		postTestPaper,
		getPaperList,
		getUserExam
	} from '@/api/index.js'
	import {
		decode64,
		formatDate,
		timeDifference
	} from '@/utils/index'
	export default {
		data() {
			return {
				startTime: '', // 开始做题时间
				endTime: '', // 交卷时间
				passNum: 85,
				radio1: 'A',
				countColor: '#000',
				list: [],
				items: [],
				text: '',
				modeType: '', // 0模拟考试 1 错题模式  2试卷模式
				haveQuestion: [], // 已经选择答题
				checkedIdx: '',
				clickIndex: '',
				unSelectedNum: [], // 未做题目
				selectedNum: [], // 已经做的题目
				chooseCorrectly: [], // 选择正确
				selectionError: [], // 选择错误
				userInfo: {},
				planId: "",
				examinationTime: '', //考试用时
				id: '', // 试卷ID
				otype: '', // 获取题库的下标
				test_paper_id: '',
				opc: '',
				paper: '', //  1 A卷 2B卷
				paperIndex: '',
				opcName: ''
			}
		},

		onLoad(val) {
			this.modeType = val.modeType
			this.opcClassId = val.opcClassId
			this.userInfo = uni.getStorageSync('userinfo')
			this.examDate = uni.getStorageSync('examDate')
			this.opc = uni.getStorageSync('opc')
			this.opcName = uni.getStorageSync('opcName')
			this.paper = uni.getStorageSync('paper')
			this.paperIndex = uni.getStorageSync('paperIndex')
			this.startTime = new Date()
			var currentTime = this.startTime.getTime();
			// 判断两个时间戳是否相等
			if (this.examDate > currentTime) {
				this.paper = 1
			} else if(val.paper == 'B') {
				this.paper = 2
			}
			this.loadData()
		},
		methods: {
			// 错题练习
			practiceError() {
				uni.redirectTo({
					url: `/pages/exercises/exercises?id=${this.id}&type=1&opc=${this.opc}`
				})
			},
			//查看试卷
			lockpaper() {
				uni.redirectTo({
					url: `/pages/exercises/exercises?id=${this.id}&type=2&opc=${this.opc}`
				})
			},
			closeBlack() {
				this.$refs.submitPopup.close()
				// uni.navigateBack();
				return
				uni.switchTab({
					url: '/pages/index/index',
				})
			},
			closePaperClose() {
				this.$refs.paperPopup.close()
			},
			myClick(val, index) {
				this.checkedIdx = val.index
				this.list[index].options[val.index].checked = !this.list[index].options[val.index].checked
				if (this.list[index].tqType == 2) {
					let item = val.item.options.map(e => {
						if (e.checked) {
							return e.value;
						}
					}).filter(value => value !== undefined);
					console.log(item);
					this.list[index].options[val.index].userAnswer = item.join()
					this.list[index].userAnswer = item.join()
				} else {
					this.list[index].options[val.index].userAnswer = val.answer
					this.list[index].userAnswer = val.answer
				}
			},
			loadData() {
				uni.showLoading({
					title: '题目获取中'
				})
				let params = {
					// opc: this.opc,
					// opcClassId: this.opcClassId,
					// paper: this.paper,
					opc: this.opc,
					opcClassId: this.opcClassId,
					paper: this.paper
				}

				getPaperList(params).then(res => {
					this.list = res.data.list.slice(0, 100).map((item, index, a) => {
						return {
							id: item.id,
							qId: item.qId,
							sortIndex: index,
							sort: item.sort,
							tqType: item.type,
							title: item.name,
							bzAnswer: item.answer,
							options: this.strSplit(item.options, item).map(p => ({
								...p,
							}))
						}
					})
					console.log(this.list);
					if (params.random == 1) {
						this.list.sort((item, index) => {
							return Math.random() - 0.5
						});
					}
					uni.hideLoading()
				})
			},
			toType(val) {
				return val
			},
			strSplit(val, item) {
				if (item.type == '3') {
					return [{
							text: `A、对`,
							value: '对'
						},
						{
							text: `B、错`,
							value: '错'
						}
					]
				} else {
					let tsStr = []
					// console.log(val,item);
					// if (!val || typeof val !== 'string') {
					// 	console.log(val,item);
					// 	return []
					// }
					tsStr = val.split('~!!~')

					const options = [];
					// 生成从 'A' 开始的字母数组，长度与 tsStr 一致
					const alphabet = Array.from({ length: tsStr.length }, (_, i) => String.fromCharCode(65 + i)); 
					tsStr.forEach((text, index) => {
						if(text) { // 确保文本不为空
							options.push({
								text: `${alphabet[index]}、${text}`,
								value: alphabet[index]
							});
						}
					});
					return options;
				}
			},
			clickItem(item, val, index) {
				document.getElementsByClassName('jump' + index)[0].scrollIntoView({
					behavior: 'auto', //定义动画过渡效果"auto"或 "smooth" 之一。默认为 "auto"。
					block: 'center', //定义垂直方向的对齐， "start", "center", "end", 或 "nearest"之一。默认为 "start"。
					inline: 'start'
				})
				if (val === 1) {
					this.$refs.paperPopup.close()
				} else {
					this.$refs.AnswersListPopup.close()
				}
			},
			AnswersListShow() {
				this.$refs.AnswersListPopup.open()
			},
			AnswersListChange() {

			},
			closeAnswersList() {
				this.$refs.AnswersListPopup.close()
			},
			// 交卷
			submitPaper() {
				console.log(this.list);
				this.unSelectedNum = [];
				this.selectedNum = []
				this.selectionError = []
				this.chooseCorrectly = []
				this.list.forEach((e, index, arr) => {
					if (!e.userAnswer) {
						this.unSelectedNum.push(e)
					} else {
						this.selectedNum.push(e)
					}
				})
				if (this.unSelectedNum.length >= 1) {
					this.$refs.paperPopup.open()
				} else {
					this.confirmPaper()
				}
			},
			// 异位判断
			areStringsAnagrams(str1, str2) {
				if (str1 === undefined || str2 === undefined) {  
				    return false;  
				  }
			  // 如果字符串长度不同，直接返回false  
			   if (str1.length !== str2.length) {  
			     return false;  
			   }  
			   
			   // 创建一个对象来统计str1中每个字符的出现次数  
			   const charCount = {};  
			   for (let char of str1) {  
			     charCount[char] = (charCount[char] || 0) + 1;  
			   }  
			   
			   // 遍历str2，减去charCount中对应字符的计数  
			   for (let char of str2) {  
			     if (!charCount[char]) {  
			       // 如果str2中有str1中没有的字符，返回false  
			       return false;  
			     }  
			     charCount[char]--;  
			   }  
			   
			   // 检查charCount对象，确保所有字符的计数都为0  
			   for (let key in charCount) {  
			     if (charCount[key] !== 0) {  
			       return false;  
			     }  
			   }  
			   
			   // 如果所有检查都通过，返回true  
			   return true;  
			},

			// 确定交卷
			confirmPaper() {
				// uni.showLoading({
				// 	mask: true,
				// 	title: '交卷计算分数中'
				// })
				this.endTime = new Date()
				this.examinationTime = timeDifference(this.startTime, this.endTime)
				this.list.map((e, i, a) => {
					if (e.userAnswer !== '') {
						if (this.areStringsAnagrams(e.bzAnswer, e.userAnswer)) {
							this.chooseCorrectly.push(e)
						} else if (e.userAnswer) {
							this.selectionError.push(e)
						}
					}
				})
				let answerRecord = this.list.map(e => {
					return {
						'id': e.qId === undefined ? e.id : 'q' + e.id,
						// 'qid': e.qId,
						userAnswer: e.userAnswer
					}
				})
				// console.log(this.chooseCorrectly,'选择正确的题目');
				// console.log(this.unSelectedNum, '未答');
				// console.log(this.selectionError, '选择错误的题目');

				let params = {
					answerRecord: answerRecord, // 题目数据
					answerIds: this.chooseCorrectly.map(e => {
						console.log(e.qId);
						return e.qId === undefined ? e.id : 'q' + e.id
					}).toString(), //  答对
					noneIds: this.unSelectedNum.map(e => {
						return e.qId === undefined ? e.id : 'q' + e.id
					}).toString(), // 未答
					errorQuestionIds: this.selectionError.map(e => {
						return e.qId === undefined ? e.id : 'q' + e.id
					}).toString(), // 答错 
					// commitTime: this.endTime.valueOf(),
					startTime: this.startTime.valueOf(), // 答题时间
					sumFalse: this.selectionError.length, //答错的数量
					sumNone: this.unSelectedNum.length, //未答的数量
					sumTrue: this.chooseCorrectly.length, // 答对的数量
					tpName: this.opcName,
					userId: this.userInfo.IDcardNum, // 身份证号码
					otype: this.opc,
					paperIndex: this.paperIndex
				}
				console.log(params);
				// this.$refs.submitPopup.open()
				// this.$refs.paperPopup.close()
				// return
				this.$refs.submitPopup.open()
				postTestPaper(params).then(res => {
					this.id = res.data.id
					uni.hideLoading()
					this.$refs.submitPopup.open()
					this.$refs.paperPopup.close()
				})
			},
			timeUpChang() {
				uni.showModal({
					title: '超时提示',
					content: '考试时间到，自动交卷',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {} else if (res.cancel) {}
					}
				});
				this.confirmPaper()
			},
			changTime(val) {
				this.countColor = '#f00';
				uni.showToast({
					title: '还剩下30分钟',
					icon: 'error',
					duration: '1000'
				});
			}
		}
	}
</script>

<style lang="less" scoped>
	.list-box {
		padding-bottom: 100rpx;
		padding-top: 80rpx;
	}

	.btm-btn {
		position: fixed;
		bottom: 0rpx;
		z-index: 2;
		width: 100%;
		display: flex;
		background-color: #f0f0f0;

		.btn {
			flex: 1;
		}
	}

	.countdown {
		position: fixed;
		top: 80rpx;
		width: 100%;
		background-color: #f0f0f0;
		z-index: 2;

		.countdown-box {
			display: flex;
			text-align: center;
			align-items: center;
			justify-content: center;
			background-color: #f0f0f0;
			padding: 8rpx;
		}

		.zw {
			height: var(--status-bar-height);
			width: 100%;
		}
	}

	.closeIcon {
		position: absolute;
		right: 36rpx;
		top: 6rpx;
		font-size: 38rpx;
		z-index: 9;
	}

	.popup-content {
		text-align: center;

		.text {
			display: block;
			padding: 8rpx 0;
		}
	}

	.ListBtns {
		display: flex;
		flex-wrap: wrap;

		.btnMin {
			padding: 0 20rpx;
			margin: 3rpx 8rpx;
			min-width: 90rpx;
		}

		.btnRad {
			background-color: #f00;
			color: #fff;
		}

		.btnGreen {
			background-color: green;
			color: #fff;
		}
	}

	.submitPopupTxt {
		text-align: center;
		padding-bottom: 20rpx;

		.popup-title {
			display: block;
			padding: 10rpx 0;
			font-size: 40rpx;
		}

		.popup-sub {
			display: block;
			padding: 0 20rpx;
			font-size: 35rpx;
		}
	}

	.paper-box {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 20rpx;

		.paper-list {
			// margin: 0 10rpx;
			padding: 0 10rpx;
			margin-bottom: 30rpx;
		}

		.btnMin {
			padding: 0 !important;
			width: 10%;
		}


		.submitPopupBtn {
			display: flex;

			.close-btn {
				flex: 1;
			}

			.submit-btn {
				flex: 1;
			}
		}
	}

	.submit-popup-box {
		background-color: #fff;
		border-radius: 20rpx;
		margin: 0 20rpx;
		width: 600rpx;

		.submitPopupTxt {}

		.popup-sub {
			padding: 5px 15rpx;
			font-size: 13px;
			border-bottom: 1px dashed #333;
		}

		.submit-name {
			display: block;
		}

		.fraction {
			display: flex;
			justify-content: center;
			align-items: baseline;
			border-bottom: 1px solid #a29f9f;

			.fraction-num {
				font-weight: bold;
				font-size: 68rpx;
			}
		}

		.timePaper {
			display: block;
			font-size: 30rpx;
			padding: 10rpx 0;
			border-bottom: 1px solid #a29f9f;
		}

		.submit-list {
			display: flex;

			.list-btn {
				// flex: 1;

			}
		}

		.prompt-box {
			display: flex;
			justify-content: space-around;
			border-bottom: 1px solid #a29f9f;
			margin-bottom: 30rpx;

			.prompt-box-txt {
				padding: 10rpx 0;
				border-left: 1px solid #a29f9f;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				flex: 1;
			}
		}
	}
</style>